package kata21;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;

public class SingleLinkedList<E> implements ISimpleList<E>{

    private SingleNode<E> node;

    @Override
    public void add(E e) {
        if(node == null){
            node = new SingleNode(e);
        }else {
            SingleNode currentNode = node;
            while (currentNode.next != null){
                currentNode = currentNode.next;
            }
            currentNode.setNext(new SingleNode(e));
        }
    }

    @Override
    public E find(E e) {
        SingleNode next = node;
        while (next != null){
            if(e.equals(next.getValue())){
                return (E)next.getValue();
            }
            next = next.getNext();
        }
        return null;
    }

    @Override
    public void delete(E e) {
        SingleNode currentNode = node;
        //第一个相等
        if(e.equals(currentNode.getValue())){
            node =  node.next;
        }else {
            //上一个
            SingleNode preNode = currentNode;
            currentNode = preNode.next;
            while (currentNode != null){
                //第一个
                if(e.equals(currentNode.getValue())){
                    //将上一个节点的下一个节点，设置为当前节点的下一个节点
                    //即当前节点别删除
                    preNode.setNext(currentNode.getNext());
                    break;
                }
                //前一个节点 <- 当前节点
                preNode = currentNode;
                //当前节点  <-  当前节点下一个节点
                currentNode = currentNode.getNext();
            }
        }

    }

    @Override
    public String values() {
        SingleNode currentNode = node;
        List<Object> result = new ArrayList<>();
        while (currentNode != null){
            result.add(currentNode.getValue());
            currentNode = currentNode.next;
        }
        return result.toString();
    }

    @Data
    static class SingleNode<T> {

        private T value;

        private SingleNode<T> next;

        public SingleNode(T value){
            this.value = value;
        }
    }
}
